<template>

  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item aria-current="true" :to="{path:'/users'}">用户管理</el-breadcrumb-item>
    <el-breadcrumb-item aria-current="false" :to="{path:'/userlist'}">用户列表</el-breadcrumb-item>
    <!--    <el-breadcrumb-item>活动详情</el-breadcrumb-item>-->
  </el-breadcrumb>

  <el-card class="box-card">


    <el-row :gutter="20">
      <el-col :span="12">
        <!--  搜索与添加区域  -->
        <el-input
            clearable
            @clear="getUsers"
            @keyup.enter="getUsers"
            v-model="queryInfo.query"
            placeholder="请输入内容">
          <template #append>
            <el-button
                @click="getUsers"
                slot="append"
                icon="el-icon-search"
            ></el-button>
          </template>
        </el-input>
      </el-col>

      <el-col :span=4>
        <el-button type="primary"
                   @click="dialogFormVisible=true">添加用户
        </el-button>
        <!--    添加对话框    -->
        <!--        v-model="addDialogVisible"-->


      </el-col>

    </el-row>


    <el-table
        border
        stripe
        :data="userList"
        style="width: 100%">
      <el-table-column
          type="index"
      >
      </el-table-column>

      <el-table-column
          prop="username"
          label="用户名"
      >
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
      >
      </el-table-column>

      <el-table-column
          prop="role_name"
          label="角色"
      >
      </el-table-column>

      <el-table-column
          prop="mg_state"
          label="状态"
      >

        <template #default="scope">
          <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
          ></el-switch>
        </template>


      </el-table-column>

      <el-table-column
          label="操作"
          width="200px"
      >
        <template #default="scope">
          <div class="btn_action">
            <el-tooltip placement="top" content="编辑用户" effect="dark">
              <el-button size="mini" type="primary" icon="el-icon-edit"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip placement="top" content="删除用户" effect="dark">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <user-role-set
                :username="scope.row.username"
                :role_name="scope.row.role_name"
                :user-id="scope.row.id"
                v-on:update="getUsers"
            >
            </user-role-set>

          </div>
        </template>
      </el-table-column>
    </el-table>

    <br>

    <!--      <add-user :addDialogVisible="showAddDialog"></add-user>-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4,5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <div v-for="o in 11" :key="o" class="text item">
      {{ '列表内容 ' + o }}


    </div>
  </el-card>

  <el-dialog
      @close="addDialogCLosed"
      title="添加用户"
      v-model="dialogFormVisible">
    <el-form :model="addUser"
             ref="addUserRef"

             :rules="addUserRoles"

    >
      <el-form-item label="用户名： " prop="username">
        <el-input v-model="addUser.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码： " prop="password">
        <el-input v-model="addUser.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱： " prop="email">
        <el-input v-model="addUser.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机：  " prop="mobil">
        <el-input v-model="addUser.mobile" autocomplete="off"></el-input>
      </el-form-item>

    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveUser()">确 定</el-button>
    </span>
    </template>
  </el-dialog>


  <el-dialog
      @close="editDialogCLosed"
      title="修改用户"
      v-model="editUserForm">
    <el-form :model="editUser"
             ref="editUserRef"
             :rules="addUserRoles">
      <el-form-item
          label="用户名： "
          prop="username">
        <el-input
            v-model="editUser.username"
            disabled
        ></el-input>
      </el-form-item>
      <el-form-item
          label="邮箱： "
          prop="email"
          :label-width="formLabelWidth">
        <el-input
            v-model="editUser.email"
            autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机：  " prop="mobile" :label-width="formLabelWidth">
        <el-input v-model="editUser.mobile" autocomplete="off"></el-input>
      </el-form-item>

    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="editUserForm = false">取 消</el-button>
      <el-button type="primary" @click="saveEditUser()">确 定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
import axios from "axios";
// const AddUser= ()=> import("@/components/user/AddUser")
import AddUser from "@/components/user/AddUser";
import {ElMessageBox} from "element-plus";
import UserRoleSet from "@/components/user/UserRoleSet";

export default {
  name: "Users",
  components: {UserRoleSet},
  // components: {AddUser},
  // components: [AddUser],


  data() {
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    const checkPhone = (rule, value, cb) => {
      console.log(value)

      const regPhone = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;

      if (regPhone.test(value)) {
        return cb()
      }

      return cb(new Error('请输入正确手机号码'))
    }
    return {
      dialogFormVisible: false,
      editUserForm: false,
      userList: [],
      //添加的用户
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editUser: {},

      addUserRoles: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 16, message: '请输入2-16个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '请输入6-16个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱 ', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ]

      },

      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
    }
  }, created() {
    this.getUsers()
  }, methods: {
    handleSizeChange(size) {
      // console.log(size);
      this.queryInfo.pagesize = size
      this.getUsers()

    },
    handleCurrentChange(currentPage) {
      // console.log(size)
      this.queryInfo.pagenum = currentPage
      this.getUsers()
    },
    addDialogCLosed() {
      //通过监听close 使用ref 清除resetFileds
      this.$refs.addUserRef.resetFields();
    },
    editDialogCLosed() {
      //通过监听close 使用ref 清除resetFileds
      this.$refs.editUserRef.resetFields();
    },
    async userStateChange(userinfo) {
      const {data: res} = await axios
          .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户数据失败')
      }
      this.$message.success('更新用户数据成功')

    },
    async getUsers() {
      const {data: res} = await axios.get('users', {params: this.queryInfo})
      console.log(res)
      if (res.meta.status !== 200) {

        return this.$message.error(res.meta.msg);
      }

      this.$message.success(res.meta.msg)

      this.userList = res.data.users
      this.total = res.data.total

    },
    saveUser() {
      console.log(this.addUser.mobil)
      this.$refs.addUserRef.validate(async valid => {
        console.log(valid)
        if (!valid) return


        const {data: res} = await axios.post('users', this.addUser)

        console.log(res)
        if (res.meta.status !== 201) {

          return this.$message.error(res.meta.msg);
        }

        this.$message.success(res.meta.msg)

        console.log(res.data)
        this.dialogFormVisible = false

      })
    },
    saveEditUser() {
      this.$refs.editUserRef.validate(async valid => {
        console.log(valid)
        if (!valid) return

        console.log(valid)
        const {data: res} = await axios.put('users/' + this.editUser.id, {
          email: this.editUser.email,
          mobile: this.editUser.mobile
        })

        console.log(res)
        if (res.meta.status !== 200) {

          return this.$message.error(res.meta.msg);
        }

        this.$message.success(res.meta.msg)

        console.log(res.data)
        this.editUserForm = false
        this.getUsers()

      })
    },
    async showEditDialog(id) {
      this.editUserForm = true
      // console.log('show'+id)
      const {data: res} = await axios.get('users/' + id);
      console.log(res)

      if (res.meta.status !== 200) {

        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg)

      this.editUser = res.data
      // this.editUserForm=false

    },

    async deleteUser(id) {
      console.log(id)


      const conres = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {


        const {data: res} = await axios.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message({
            type: 'info',
            message: '删除失败!'
          });
          return
        }

        this.$message.success(res.meta.msg)


        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getUsers()

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

      console.log(conres)


    },
  }
}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: auto;
}

.btn_action {
  text-align: center;
}
</style>